﻿#pragma once
#include"lexel.h"
#include<stdbool.h>
#include<malloc.h>
char* tlist_symbol = "~!@#$%^&*()-=+/[]";
char* tlist_keyword[5] = { "var","as","def","tab","ret" };
bool IsKeyword(char* c)
{
	for (int i = 0; i < 5; i++)
	{
		if (strcmp(c, tlist_keyword[i]) == 0)
			return true;
	}
	return false;
}
bool WIsNumber(char c)
{
	if (c >= '0' && c <= '9')
		return true;
	return false;
}
bool WIsWord(char c)
{
	if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') && c != ' ' && c != '\0')
		return true;
	return false;
}
bool WIsSymbol(char c)
{
	char* tmp = tlist_symbol;
	while (*tmp)
	{
		if (*tmp == c)
			return true;
		tmp++;
	}
	return false;
}
bool WIsSplit(char c)
{

}

bool IsWords(char* c)
{
	char* tmp = c;
	if (strcmp(tmp, "") == 0)
		return false;
	while (*tmp)
	{
		if (!WIsWord(*tmp))
			return false;
		tmp++;
	}

	return true;
}
bool IsNumber(char* c)
{
	char* tmp = c;
	while (*tmp)
	{
		if (!WIsNumber(*tmp))
			return false;
		tmp++;
	}
	return true;
}
QToken* MakeToken(int type, char* value, int row, int line)
{
	QToken* re = malloc(sizeof(QToken));
	if (re == NULL)
		return NULL;
	re->value = malloc(sizeof(value));
	strcpy(re->value, value);
	re->type = type;
	re->line = line;
	re->row = row;
	return re;
}
void AddToken(QToken* t, QTokenList* tl)
{
	if (tl == NULL || t == NULL)
		return;
	tl->tlist[tl->cur] = *t;
	tl->cur++;

}
QLexerErr* MakeErr(int row, int line, char* info)
{
	QLexerErr* le = malloc(sizeof(QLexerErr));
	if (le == NULL)
		return NULL;
	le->info = info;
	le->row = row;
	le->line = line;
	return le;
}
QLexerErr* QLexerMake(char* txt, QTokenList* tk)
{
	char* codes = txt;
	int crow = 0, cline = 0;
	char now_str[100] = "";
	int cout = 0;
	int strl = strlen(codes);
	while (*codes)
	{
		if (WIsSymbol(*codes) || *codes == ' ' || *codes == '\n')
		{
			if (strcmp(now_str, "") != 0)
			{
				if (IsKeyword(now_str))
					AddToken(MakeToken(TT_KEYWORD, now_str, crow, cline), tk);
				else if (IsWords(now_str))
					AddToken(MakeToken(TT_WORD, now_str, crow, cline), tk);
				else if (IsNumber(now_str))
					AddToken(MakeToken(TT_NUM, now_str, crow, cline), tk);
				else return MakeErr(crow, cline, "Unknow word(s)!");
				memset(now_str, '\0', sizeof(char) * strlen(now_str));
			}
			if (*codes == '\n')
			{
				cline++;
			}
			else if (*codes != ' ')
			{
				char ca[2] = { 0 };
				ca[0] = *codes;
				//首先判断是否为符号，作为分割依据
				if (WIsSymbol(*(codes + 1)))
				{
					//双目运算符
					codes++;
					ca[1] = *codes;
				}
				AddToken(MakeToken(TT_SYMBOL, ca, crow, cline), tk);
			}
			crow++;
		}
		else if (WIsWord(*codes) || WIsNumber(*codes))
		{
			if (strlen(now_str) >= 100)
				return MakeErr(crow, cline, "Strings out of buf.");
			now_str[strlen(now_str)] = *codes;
		}
		codes++;
		cout++;
	}
	return NULL;
}
